<template>
  <view>
    <view class="clockIn-box">
      <view class="box-left">
        <view class="box-left-top-title">{{nowDate}}</view>
        <view class="box-left-top-content">
          <!-- <view class="box-left-temperature-number">28</view> -->
          <view class="box-left-temperature-number">{{temperature}}</view>
          <view class="box-left-temperature-unit">℃</view>
        </view>
      </view>
      <view class="box-middle">
        <view class="clockIn-button" @click="clockIn">{{clockInText}}</view>
      </view>
      <view class="box-right">
        <view class="box-right-title">打卡天数</view>
        <view class="box-right-content">
          <view class="box-right-number" v-if="token">{{clockInList.length}}</view>
          <view class="box-right-number" v-else>0</view>
        </view>
      </view>
    </view>
    <view class="data-box">
      <view class="data-box-left" @click="gotoInformation">
        <view class="box-left-title">身体数据</view>
        <view class="box-left-content">
          <view class="box-left-weight">体重：{{userinfo.userWeight? userinfo.userWeight + 'kg' : '未填写'}}</view>
          <view class="box-left-bmi">体脂率：{{userinfo.userBMI? userinfo.userBMI + '%' : '未填写'}}</view>
        </view>
      </view>
      <view class="data-box-right">
        <view class="box-right-title">运动数据</view>
        <view class="box-right-content">
          <view class="box-right-duration">运动时长：{{motionDuration}}min</view>
          <view class="box-right-calorie">消耗卡路里：{{consumeCalorie}}kcal</view>
        </view>
      </view>
    </view>

    <view class="box-top-title">今日计划</view>
    <view class="plan-box">
      <view class="example-body">
        <uni-datetime-picker v-model="planDate" type="date" @change="getPlanList">{{planDate}}</uni-datetime-picker>
      </view>
      <view class="plan-prompt" v-if="!token">未登录</view>
      <view class="plan-prompt" v-if="token && userPlan.length<=0">今天还没有运动计划哦~</view>
     <scroll-view class="plan-scroll" scroll-y v-else :scroll-top="planScrollTop" v-if="token && userPlan.length>0">
        <view class="plan-content" v-for="(item, i) in userPlan" :key="i">
          <view class="plan-content-time">{{item.dateTime}}</view>
          <view class="plan-content-text">{{item.content}}</view>
        </view>
      </scroll-view>
      <view class="plan-details" v-if="token && userPlan.length>0" @click="gotoPlanPage">
        <view class="plan-details-text">查看更多</view>
        <uni-icons class="plan-details-icon" type="forward" size="13" color="#ccc"></uni-icons>
      </view>
    </view>

    <view class="box-top-title">今日运动</view>
    <view class="record-box">
      <view class="example-body">
        <uni-datetime-picker v-model="recordDate" type="date"
          @change="getRecordList">{{recordDate}}</uni-datetime-picker>
      </view>
      <view class="record-prompt" v-if="!token">未登录</view>
     <view class="record-prompt" v-if="token && (!userRecord.record || userRecord.record.length<=0)">今天还没有运动记录哦~</view>
      <view class="record-title" v-if="userRecord.record && userRecord.record.length>0">
        <view class="record-title-number">序号</view>
        <view class="record-title-type">运动部位</view>
        <view class="record-title-project">运动项目</view>
        <view class="record-title-time">运动时间</view>
      </view>
      <scroll-view class="record-scroll" scroll-y v-if="userRecord.record && userRecord.record.length>0"
        :scroll-top="recordScrollTop">
        <view class="record-scroll-box" v-for="(item, i) in userRecord.record" :key="i">
          <view class="record-item">
            <view class="record-number">{{item.number}}</view>
            <view class="record-type">{{item.type}}</view>
            <view class="record-project">{{item.project}}</view>
            <view class="record-time">{{item.time}}</view>
          </view>
        </view>
      </scroll-view>
      <view class="record-details" v-if="userRecord.record && userRecord.record.length>0" @click="gotoRecordPage">
        <view class="record-details-text">查看更多</view>
        <uni-icons class="record-details-icon" type="forward" size="13" color="#ccc"></uni-icons>
      </view>
    </view>
    <view class="box"></view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  export default {
    data() {
      return {
        // 今天日期
        nowDate: '',
        // 今天温度
        temperature: 0,
        // 打卡按钮文本
        clockInText: '打卡',
        // 运动时长
        motionDuration: 0,
        // 消耗的卡路里
        consumeCalorie: 0,
        // 运动计划日期
        planDate: '',
        // 运动记录日期
        recordDate: '',
        // 运动计划
        userPlan: [],
        // 运动记录
        userRecord: {},
        // 运动记录盒子滚动条高度
        recordScrollTop: 0,
        // 运动计划盒子滚动条高度
        planScrollTop: 0,
      };
    },
    computed: {
      ...mapState('m_user', ['token', 'userinfo', 'planList', 'recordList', 'todayRecord', 'clockInList'])
    },
    onLoad() {
      this.nowDate = this.getNowDate()
      if (this.token) {
        setTimeout(() => {
          // 调用获取运动计划方法
          this.getPlanList(this.nowDate)
          // 调用获取运动记录方法
          this.getRecordList(this.nowDate)
          // 调用获取用户运动时长
          this.getMotionDuration()
          // 调用判断用户是否已打卡方法
          this.isClockIn(this.nowDate);
        }, 500); // 延迟执行，等待用户所有数据获取完成
      }
      const that = this
      // 通过授权位置信息获取用户位置天气情况
      uni.getLocation({
        success: res => {
          console.log(res)
          const latitude = res.latitude
          const longitude = res.longitude
          console.log(latitude)
          console.log(longitude)
          uni.request({
            url: 'https://api.seniverse.com/v3/weather/now.json?key=SNK94Hdo7PWRIKPuE&location=' + latitude + ':' + longitude + '&language=zh-Hans&unit=c',
            success: function(res) {
              console.log(res)
              const temperature = res.data.results[0].now.temperature
              const weather = res.data.results[0].now.text
              that.temperature = temperature
              console.log('天气：' + weather + ', 温度：' + temperature + '度')
            },
            fail: function(err) {
              console.log('请求失败')
            }
          })
        },
        fail: res => {
          console.log(res)
        }
      })
    },
    onShow() {
      if (this.token) {
        // 调用获取运动计划方法
        this.getPlanList(this.nowDate)
        // 调用获取运动记录方法
        this.getRecordList(this.nowDate)
        // 调用获取用户运动时长
        this.getMotionDuration()
        // 调用判断用户是否已打卡方法
        this.isClockIn(this.nowDate);
      }
    },
    methods: {
      ...mapMutations('m_user', ['updateUserClockInList']),
      // 获取当前日期事件
      getNowDate() {
        // 获取当前日期
        const date = new Date();
        const year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        // 添加0前缀
        if (month < 10) {
          month = '0' + month;
        }
        if (day < 10) {
          day = '0' + day;
        }
        const formattedDate = `${year}-${month}-${day}`;
        this.planDate = formattedDate
        this.recordDate = formattedDate
        return formattedDate
      },
      // 判断今天用户是否已打卡事件
      isClockIn(date) {
        const exists = this.clockInList.some(obj => obj.date === date);
        if (exists) { // 存在
          this.clockInText = '已打卡'
        } else { // 不存在
          this.clockInText = '打卡'
        }
      },
      // 点击打卡事件
      async clockIn() {
        if(!this.token) return uni.$showMsg('请先登录')
        if (this.clockInText === '打卡') {
          this.clockInText = '已打卡'
          // 准备参数
          var token = uni.getStorageSync('token')
          const clockInDate = {
            date: this.nowDate,
            info: '已打卡',
          }
          const query = {
            token,
            clockInDate,
          }
          this.clockInDays++

          const {
            data: res
          } = await uni.$http.post('/api/update/clockIn', query)
          console.log(res.message)
          this.updateUserClockInList(res.message)
          return uni.$showMsg('打卡成功')
        }
      },
      // 获取用户当天的运动时长
      getMotionDuration() {
        if (this.userRecord.record === undefined) return
        const totalSeconds = this.userRecord.record.reduce((sum, item) => {
          const [hours, minutes, seconds] = item.time.split(':');
          const durationInSeconds = parseInt(hours) * 3600 + parseInt(minutes) * 60 + parseInt(seconds);
          return sum + durationInSeconds;
        }, 0);
        // 将总秒数转换成分钟
        const totalMinutes = Math.floor(totalSeconds / 60)
        // 将分钟数作为字符串赋值给 motionDuration 变量
        this.motionDuration = totalMinutes

        const avgCaloriesPerMinute = 5 // 平均每分钟消耗的卡路里数
        this.consumeCalorie = this.motionDuration * avgCaloriesPerMinute
      },
      // 获取用户对应日期的运动计划事件
      getPlanList(date) {
        if(!this.token) return uni.$showMsg('请先登录')
        const formattedDate = this.dateFormatConversion(date);
        const plans = this.planList.filter(plan => plan.date === formattedDate);
        if (plans.length === 0) {
          this.userPlan = [];
        } else {
          this.userPlan = plans;
        }
        this.planScrollTop = this.planScrollTop ? 0 : 0.1
      },
      // 获取用户对应日期的运动记录事件
      getRecordList(date) {
        if(!this.token) return uni.$showMsg('请先登录')
        const record = this.recordList.find(record => record.date === date)
        if (record === undefined) {
          this.userRecord = {}
        } else {
          this.userRecord = record
        }
        this.recordScrollTop = this.recordScrollTop ? 0 : 0.1
      },

      // 运动计划的日期选择器日期返回事件
      changePlan(e) {
        this.planDate = e;
      },
      // 运动记录的日期选择器日期返回事件
      changeRecord(e) {
        this.recordDate = e;
      },
      // 日期格式转换事件
      dateFormatConversion(dateString) {
        const dateArr = dateString.split('-');
        const year = dateArr[0];
        const month = parseInt(dateArr[1], 10);
        const date = parseInt(dateArr[2], 10);
        const formattedDate = `${year}年${month}月${date}日`;
        return formattedDate;
      },
      // 跳转到个人资料页面事件
      gotoInformation() {
        if(this.token === ''){
          uni.switchTab({
            url: '../../pages/my/my'
          })
        }else {
          uni.navigateTo({
            url: '../../subpkg/my_information/my_information'
          })
        }
      },
      // 跳转到运动计划页面事件
      gotoPlanPage() {
        uni.navigateTo({
          url: '../../subpkg/plan/plan'
        })
      },
      // 跳转到运动记录页面事件
      gotoRecordPage() {
        uni.navigateTo({
          url: '../../subpkg/record/record'
        })
      },
    }
  }
</script>

<style lang="scss">
  // 隐藏滚动条
  ::-webkit-scrollbar {
    width: 0;
    height: 0;
    color: transparent;
  }

  .clockIn-box {
    height: 260rpx;
    border-radius: 15rpx;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    margin: 30rpx;
    background: white;
    box-shadow: 0px 1px 2px 0.1px #ddd;

    .box-left {
      height: 200rpx;
      width: 210rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin: 20rpx 0rpx 20rpx 20rpx;
      border-radius: 15rpx;

      .box-left-top-title {
        color: black;
        font-size: 30rpx;
        font-weight: 400;
        margin-bottom: 20rpx;
      }

      .box-left-top-content {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;

        .box-left-temperature-number {
          color: black;
          font-size: 60rpx;
          font-weight: 300;
        }

        .box-left-temperature-unit {
          color: black;
          font-size: 30rpx;
          margin-bottom: auto;
        }
      }

      .box-left-bootom {
        width: 210rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-content: center;

        .box-left-bootom-title {
          color: grey;
          font-size: 34rpx;
          font-weight: bold;
          text-align: center;
          margin-bottom: 10rpx;
        }

        .box-left-bootom-content {
          display: flex;
          flex-direction: row;
          justify-content: center;
          align-items: center;
          color: gray;

          .box-left-bootom-temperature {
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            margin-right: 20rpx;

            .box-left-bootom-temperature-number {
              font-size: 60rpx;

            }

            .box-left-bootom-temperature-unit {
              font-size: 30rpx;

              margin-bottom: auto;
            }
          }

          .box-left-bootom-text {
            font-size: 28rpx;
            font-weight: bold;

          }
        }
      }
    }

    .box-middle {
      height: 300rpx;
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;

      .clockIn-button {
        height: 180rpx;
        width: 180rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 50%;
        color: white;
        font-weight: bold;
        font-size: 45rpx;
        background: linear-gradient(to bottom right, #fba007, #f0c114);
        box-shadow: 0px 1px 2px 0.1px #ddd;
      }
    }

    .box-right {
      height: 200rpx;
      width: 210rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin: 20rpx 20rpx 20rpx 0rpx;
      border-radius: 15rpx;


      .box-right-title {
        color: black;
        font-size: 30rpx;
        font-weight: 400;
        margin-bottom: 20rpx;
      }

      .box-right-number {}

      .box-right-content {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;

        .box-right-number {
          font-size: 60rpx;
          color: #fba007;
        }

      }
    }
  }

  .data-box {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    margin: 0 30rpx;
    justify-content: space-between;

    .data-box-left {
      text-align: left;
      height: 210rpx;
      width: 320rpx;
      border-radius: 15rpx;
      box-shadow: 0px 1px 2px 0.1px #ddd;

      background: white;


      .box-left-title {
        font-weight: bold;
        font-size: 32rpx;
        margin-bottom: 25rpx;
        padding: 10rpx 0;
        text-align: center;
        color: white;
        letter-spacing: 1rpx;
        border-top-left-radius: 15rpx;
        border-top-right-radius: 15rpx;
        background: linear-gradient(to bottom right, #fba007, #f0c114);
      }

      .box-left-content {
        border-radius: 15rpx;
        margin: 0 20rpx;

        .box-left-weight {
          font-weight: 400;
          font-size: 30rpx;
          color: black;
          margin-bottom: 10rpx;
        }

        .box-left-bmi {
          font-weight: 400;
          font-size: 30rpx;
          color: black;
        }
      }
    }

    .data-box-right {
      text-align: left;
      height: 210rpx;
      width: 320rpx;
      border-radius: 15rpx;
      box-shadow: 0px 1px 2px 0.1px #ddd;
      background: white;


      .box-right-title {
        font-weight: bold;
        font-size: 32rpx;
        margin-bottom: 25rpx;
        padding: 10rpx 0;
        text-align: center;
        color: white;
        letter-spacing: 1rpx;
        border-top-left-radius: 15rpx;
        border-top-right-radius: 15rpx;
        background: linear-gradient(to bottom right, #fba007, #f0c114);
      }

      .box-right-content {
        border-radius: 15rpx;
        margin: 0 20rpx;

        .box-right-duration {
          font-weight: 400;
          font-size: 30rpx;
          color: black;
          margin-bottom: 10rpx;
        }

        .box-right-calorie {
          font-weight: 400;
          font-size: 30rpx;
          color: black;
        }
      }
    }
  }

  .box-top-title {
    height: 45rpx;
    line-height: 45rpx;
    font-weight: bold;
    font-size: 32rpx;
    letter-spacing: 1rpx;
    margin: 30rpx 30rpx 20rpx 30rpx;
    color: black;
    border-left: 5px solid #f8a32a;
    padding-left: 20rpx;
  }

  .plan-box {
    min-height: 230rpx;
    max-height: 570rpx;
    border-radius: 15rpx;
    display: flex;
    flex-direction: column;
    margin: 0rpx 30rpx 20rpx 30rpx;
    background-color: white;
    box-shadow: 0px 1px 2px 0.1px #ddd;

    .example-body {
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      padding: 0 240rpx;
      border-top-left-radius: 15rpx;
      border-top-right-radius: 15rpx;
      // color: gray;
      color: white;
      font-weight: bold;
      // margin-bottom: 30rpx;
      background: linear-gradient(to bottom right, #fba007, #f0c114);

    }

    .plan-prompt {
      height: 170rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #ccc;
      text-align: center;
    }

    .plan-scroll {
      margin-top: 30rpx;
      max-height: 390rpx;
      overflow: hidden;

      .plan-content {
        text-align: center;
        margin: 0rpx 30rpx 20rpx 30rpx;
        padding: 20rpx 20rpx;
        background-color: whitesmoke;
        border-radius: 15rpx;
        border: 1px solid #eee;

        .plan-content-time {
          margin-bottom: 10rpx;
          font-size: 28rpx;
        }

        .plan-content-text {
          text-align: left;
          text-indent: 2em;
          letter-spacing: 1px;
          font-size: 28rpx;
        }
      }
    }

    .plan-details {
      width: 130rpx;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      padding: 10rpx 0;
      margin: 10rpx 30rpx 10rpx auto;
      color: #ccc;

      .plan-details-text {
        font-size: 26rpx;
      }

      .plan-details-icon {
        padding-bottom: 4rpx;
      }
    }
  }

  .record-box {
    min-height: 250rpx;
    max-height: 570rpx;
    border-radius: 15rpx;
    display: flex;
    flex-direction: column;
    margin: 0 30rpx 20rpx 30rpx;
    background: white;
    box-shadow: 0px 1px 2px 0.1px #ddd;


    .example-body {
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      padding: 0 240rpx;
      border-top-left-radius: 15rpx;
      border-top-right-radius: 15rpx;
      color: white;
      font-weight: bold;
      background: linear-gradient(to bottom right, #fba007, #f0c114);
    }

    .record-prompt {
      height: 170rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #ccc;
      text-align: center;
    }

    .record-title {
      margin: 30rpx 30rpx 20rpx 30rpx;
      display: flex;
      align-items: center;
      text-align: center;
      padding: 0 20rpx;
      font-size: 28rpx;
      letter-spacing: 1rpx;
      font-weight: bold;

      .record-title-number {
        width: 60rpx;
      }

      .record-title-type {
        width: 170rpx;
      }

      .record-title-project {
        flex: 1;
        padding-right: 63rpx;
      }

      .record-title-time {
        width: 150rpx;
        padding-right: 3rpx;
      }
    }

    .record-scroll {
      max-height: 325rpx;
      overflow: hidden;


      .record-scroll-box {

        .record-item {
          height: 85rpx;
          display: flex;
          align-items: center;
          text-align: center;
          margin: 0rpx 30rpx 20rpx 30rpx;
          padding: 0 20rpx;
          background-color: whitesmoke;
          border-radius: 15rpx;
          font-size: 26rpx;
          border: 1px solid #eee;

          .record-number {
            width: 50rpx;
          }

          .record-type {
            width: 120rpx;
            text-align: right;
          }

          .record-project {
            flex: 1;
          }

          .record-time {
            width: 150rpx;
          }
        }
      }
    }

    .record-details {
      width: 130rpx;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      padding: 10rpx 0;
      margin: 10rpx 30rpx 10rpx auto;
      color: #ccc;

      .record-details-text {
        font-size: 26rpx;
      }

      .record-details-icon {
        padding-bottom: 4rpx;
      }
    }
  }

  .box {
    height: 1rpx;
  }
</style>